import { login, logout, getInfo, getMenusAsync, rootmenus, convertTree } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ Name: username.trim(), Pwd: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token) // token 存入 store
        commit('SET_INTRODUCTION', '用户说明')
        commit('SET_NAME', data.user.name)
        commit('SET_AVATAR', data.user.photo)
        commit('SET_ROLES', data.user.role)
        setToken(data.token) // 将token存入cookie
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取服务器菜单
  async getMenus({ commit }, roleIds) {
    return new Promise((resolve, reject) => {
      getMenusAsync(roleIds).then(res => {
        const menuRouters = rootmenus(res)
        convertTree(menuRouters, res) // 用递归填充
        return resolve(menuRouters)
      })
        .catch(err => err)
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 根据 token 获取用户信息
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('身份验证错误，请重新登录！')
        }
        const { roles, name, avatar, introduction } = data

        // roles是一个非空数组
        if (!roles || roles.length <= 0) {
          reject('希望服务返回一个角色数据，但是没有。')
        }

        commit('SET_ROLES', roles) // 存放角色
        commit('SET_NAME', name) // 存放 姓名
        commit('SET_AVATAR', avatar) // 存放头像
        commit('SET_INTRODUCTION', introduction) // 存放介绍
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // 重新设置全息（重新登录）
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
